<?php
/**
 *  MyApp_Util.php
 *
 */

/**
 *  MyApp_Util
 *
 *  @access     public
 */
class MyApp_Util
{
    /**
     *
     *  @access public
     *  @param  int  $year
     *  @param  int  $year
     *  @param  int  $year
     *  @return int
     */
    function getAge($year, $mon, $mday)
    {
        $birthday = sprintf('%04d%02d%02d', $year, $mon, $mday);
        $nowdate = date('Ymd');

        return (int) (((int) $nowdate - (int) $birthday) / 10000);
    }


    /**
     *
     *  $max_width x $max_height
     *
     *  @access public
     *  @param  string  $fname
     *  @param  int     $max_width
     *  @param  int     $max_height
     *  @param  string  $new_fname
     *  @param  int     $quality
     *  @return boolean    true:false:
     */
    function resizeFileImage($fname, $max_width, $max_height, $new_fname, $quality = 75)
    {
        // Check if GD extension is loaded
        if (!extension_loaded('gd') && !extension_loaded('gd2')) {
            trigger_error("GDライブラリがロードできません", E_USER_WARNING);
            return false;
        }

        // Get Image size info
        $result = getimagesize($fname);
        if (!$result) {
            trigger_error("イメージ情報が取得できません", E_USER_WARNING);
            return false;
        }
        list($orig_width, $orig_height, $image_type) = $result;

        switch ($image_type) {
            case 1: $im = imagecreatefromgif($fname); break;
            case 2: $im = imagecreatefromjpeg($fname);  break;
            case 3: $im = imagecreatefrompng($fname); break;
            default: trigger_error('サポートしていないファイル形式です', E_USER_WARNING); return false;
        }

        if (!$im) {
            trigger_error("イメージがロードできません", E_USER_WARNING);
            return false;
        }

        $new_width = $orig_width;
        $new_height = $orig_height;

        if ($orig_width > $max_width || $orig_height > $max_height) {

            $width_ratio = $max_width / $orig_width;
            $height_ratio = $max_height / $orig_height;

            if($width_ratio > $height_ratio) {
                $new_height = $max_height;
                $new_width = ($orig_width * $new_height) / $orig_height;
            } else {
                $new_width = $max_width;
                $new_height = ($orig_height * $new_width) / $orig_width;
            }
        }

        $newImg = imagecreatetruecolor($new_width, $new_height);
        if (!$newImg) {
            trigger_error("イメージファイルの作成に失敗しました", E_USER_WARNING);
            imagedestroy($im);
            return false;
        }

        if (($image_type == 1) OR ($image_type==3)) {
            imagealphablending($newImg, false);
            imagesavealpha($newImg, true);
            $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
            imagefilledrectangle($newImg, 0, 0, $new_width, $new_height, $transparent);
        }
        if (!imagecopyresampled($newImg, $im, 0, 0, 0, 0, $new_width, $new_height, $orig_width, $orig_height)) {
            trigger_error("イメージのリサイズ処理に失敗しました", E_USER_WARNING);
            imagedestroy($im);
            imagedestroy($newImg);
            return false;
        }

        switch ($image_type) {
            case 1: $result = imagegif($newImg, $new_fname); break;
            case 2: $result = imagejpeg($newImg, $new_fname, $quality); break;
            case 3: $result = imagepng($newImg, $new_fname); break;
            default: trigger_error('サポートしていないファイル形式です', E_USER_WARNING);
                imagedestroy($im);
                imagedestroy($newImg);
                return false;
        }
        if (!$result) {
            trigger_error("イメージファイルの書き出しに失敗しました", E_USER_WARNING);
            imagedestroy($im);
            imagedestroy($newImg);
            return false;
        }

        imagedestroy($im);
        imagedestroy($newImg);

        return true;
    }

    /**
     *
     *  @access public
     *  @param  string  $data
     *  @param  int     $width 
     *  @param  int     $height
     *  @return string
     */
    function resizeBinaryImageToFile($data, $max_width, $max_height, $new_fname, $quality = 75)
    {
        // Check if GD extension is loaded
        if (!extension_loaded('gd') && !extension_loaded('gd2')) {
            trigger_error("GDライブラリがロードできません", E_USER_WARNING);
            return false;
        }

        $im = imagecreatefromstring($data);
        if (!$im) {
            trigger_error("イメージがロードできません", E_USER_WARNING);
            return false;
        }

        $orig_width = imagesx($im);
        $orig_height = Imagesy($im);

        $new_width = $orig_width;
        $new_height = $orig_height;

        if ($orig_width > $max_width || $orig_height > $max_height) {

            $width_ratio = $max_width / $orig_width;
            $height_ratio = $max_height / $orig_height;

            if($width_ratio > $height_ratio) {
                $new_height = $max_height;
                $new_width = ($orig_width * $new_height) / $orig_height;
            } else {
                $new_width = $max_width;
                $new_height = ($orig_height * $new_width) / $orig_width;
            }
        }

        $newImg = imagecreatetruecolor($new_width, $new_height);
        if (!$newImg) {
            trigger_error("イメージファイルの作成に失敗しました", E_USER_WARNING);
            imagedestroy($im);
            return false;
        }

        if (!imagecopyresampled($newImg, $im, 0, 0, 0, 0, $new_width, $new_height, $orig_width, $orig_height)) {
            trigger_error("イメージのリサイズ処理に失敗しました", E_USER_WARNING);
            imagedestroy($im);
            imagedestroy($newImg);
            return false;
        }

        $result = imagejpeg($newImg, $new_fname, $quality);
        if (!$result) {
            trigger_error("イメージファイルの書き出しに失敗しました", E_USER_WARNING);
            imagedestroy($im);
            imagedestroy($newImg);
            return false;
        }

        imagedestroy($im);
        imagedestroy($newImg);

        return true;
    }

    /**
     *
     *  $key
     *
     *  @access public
     *  @param  string $base
     *  @param  string $key
     *  @return string
     */
    function getDepthDir($base, $key)
    {
        $len = strlen($key);

        $dir1 = substr($key, 0, 2);
        if ($len-2 < 0 || strlen($dir1) < 2) {
            $dir1 = "__dir1";
        }
        $dir2 = substr($key, 2, 2);
        if ($len-4 < 0 || strlen($dir2) < 2) {
            $dir2 = "__dir2";
        }

        return sprintf("%s/%s/%s", $base, $dir1, $dir2);
    }

    /**
     *
     *  @access public
     *  @param  int  $total
     *  @param  int  $offset
     *  @param  int  $count
     *  @return array
     */
    function getPager($total, $offset, $count, $action = null)
    {
        $dll = Ethna_Util::getDirectLinkList($total, $offset, $count);

        $next = $offset + $count;
        if ($next < $total) {
            $last = ceil($total / $count);
            $pager['hasnext'] = true;
            $pager['next'] = $next;
            $pager['last'] = ($last * $count) - $count;
        }
        $prev = $offset - $count;
        if (($offset - $count) >= 0) {
            $pager['hasprev'] = true;
            $pager['prev'] = $prev;
        }
        $pager['current'] = $offset;
        $pager['total'] = $total;
        $pager['action'] = $action;
        $pager['list'] = $dll;
        $pager['action'] = $action;

        return $pager;
    }

    function getPager2($cur_page, $total_items, $limit_per_page = 20, $page_range = 9, $action = null, $params = array()) {

        $total_pages = ceil($total_items / $limit_per_page);

        if($cur_page + floor($page_range / 2) < $total_pages) {
            $pageFrom = $cur_page - floor($page_range / 2);
            if($pageFrom < 1) $pageFrom = 1;

            $pageTo = $pageFrom + $page_range - 1;
            if($pageTo > $total_pages) $pageTo = $total_pages;
        } else {
            $pageTo = $total_pages;

            $pageFrom = $pageTo - ($page_range - 1);
            if($pageFrom < 1) $pageFrom = 1;
        }

        $pageArray = array();
        for($i = $pageFrom; $i <= $pageTo; $i++) {
            $pageArray[] = $i;
        }

        $from = ($cur_page - 1) * $limit_per_page;
        $to = $from + $limit_per_page - 1;
        if($to > $total_items - 1) $to = $total_items - 1;

        if ($total_items > 0) {
            $isFirst = ($cur_page == 1);
            $isLast = ($cur_page == $total_pages);
            $isOut = ($cur_page < 1 || $cur_page > $total_pages);
        } else {
            $isFirst = true;
            $isLast = true;
            $isOut = true;
        }

        $pageInfo['curPage'] = $cur_page;
        $pageInfo['totalPages'] = $total_pages;
        $pageInfo['pageFrom'] = $pageFrom;
        $pageInfo['pageTo'] = $pageTo;
        $pageInfo['pageList'] = $pageArray;
        $pageInfo['totalItems'] = $total_items;
        $pageInfo['itemFrom'] = $from;
        $pageInfo['itemTo'] = $to;
        $pageInfo['isFirstPage'] = $isFirst;
        $pageInfo['isLastPage'] = $isLast;
        $pageInfo['isOut'] = $isOut;
        $pageInfo['action'] = $action;
        $pageInfo['params'] = $params;

        return $pageInfo;
    }

    /**
     *
     *  @access public
     *  @param  string  $line
     *  @return array
     */
    function getExcelCsv($line)
    {
        $data = array();
        $line = str_replace('""', '”', $line);
        $len = strlen($line);
        $ncols = 0;
        $i = 0;
        while ($i <= $len) {
            if ($line[$i] == "\r" || $line[$i] == "\n") {
                break;
            } elseif ($line[$i] == "\"") {
                $i++;
                for ($j = $i; $j < $len; $j++) {
                    if ($line[$j] == "\"") {
                        break;
                    }
                }
                $data[$ncols] = substr($line, $i, $j - $i);
                $i = $j + 2;
            } else {
                for ($j = $i; $j < $len; $j++) {
                    if ($line[$j] == "," || $line[$j] == "\r" || $line[$j] == "\n") {
                        break;
                    }
                }
                $data[$ncols] = substr($line, $i, $j - $i);
                $i = $j + 1;
            }
            $ncols++;
        }
        for ($i = 0; $i < count($data); $i++) {
            $data[$i] = str_replace("”", "\"", $data[$i]);
        }
        return $data;
    }

    /**
     *
     *  @access public
     *  @param  string  $format
     *  @param  int     $timstamp
     *  @return string
     */
    function getJDate($format, $timestamp = null)
    {
        if ($timestamp === null) {
            $timestamp = time();
        }

        $ymd = date('Ymd', $timestamp);
        $year = date('Y', $timestamp);
        if ($ymd <= "19120729") {
            $label = "明治";
            $wareki = $year - 1867;
        } else if ($ymd >= "19120730" && $ymd <= "19261224") {
            $label = "大正";
            $wareki = $year - 1911;
        } else if ($ymd >= "19261225" && $ymd <= "19890107") {
            $label = "昭和";
            $wareki = $year - 1925;
        } else if ($ymd >= "19890108") {
            $label = "平成";
            $wareki = $year - 1988;
        }

        $ret = date($format, $timestamp);
        $ret = str_replace('V', $label, $ret);
        $ret = str_replace('v', $wareki, $ret);

        return $ret;
    }


    /**
     *
     *  @access public
     *  @param  array  $tmp_Create_Image_id
     *  @param  int     $fl
     */
    function Create_Image_File(&$tmp_Create_Image_id,$fl){


        $base_dirs = $this->backend->getConfig()->get('base_path');
        $base_dir = $this->backend->getConfig()->get('document_root');
        $img_path = $this->backend->getConfig()->get('blog_image_path');

        foreach($tmp_Create_Image_id as $kk=>$vv){

            $file_name="";

            if($fl=="1"){
                $file_name = $base_dir.$img_path.md5($vv).'44';
            }elseif($fl=="2"){
                $file_name = $base_dir.$img_path.md5($vv).'80';
            }elseif($fl=="3"){
                $file_name = $base_dir.$img_path.md5($vv).'61';
            }else{
                $file_name = $base_dir.$img_path.md5($vv).'';
            }

            if(file_exists($file_name)){
            }else{
                $params = array(
                    'user_id'=>$vv
                );

                $this->db_r = $this->backend->getDB('r');
                $sql = "select user_image_file from m_user_profile where user_id = ? ";
                $params = array(
                    $vv
                );

                $result = &$this->db_r->db->query($sql,$params);
                while($row = $result->fetchRow()){
                    $data = $row;
                }

                $c = $data[0];
                if($c!=""){

                    if($fl=="1"){
                        $fname = MyApp_Util::resizeBinaryImage(stripslashes($c),'44','43');
                    }elseif($fl=="2"){
                        $fname = MyApp_Util::resizeBinaryImage(stripslashes($c),'80','81');
                    }elseif($fl=="3"){
                        $fname = MyApp_Util::resizeBinaryImage(stripslashes($c),'61','53');
                    }else{
                        $fname = stripslashes($c);
                    }
                    $fp = fopen($file_name, 'w');
                    fputs($fp, $fname);
                    fclose($fp);
                }else{


                }
            }
        }

    }

    /**
     *
     *  @access public
     *  @param  string $path1
     *  @param  string $path2
     *  @return string
     */
    function joinPath($path1, $path2)
    {
        $ret;
        $tail_slash = preg_match('/\/$/' , $path1);
        $head_slash = preg_match('/^\//' , $path2);

        if ($tail_slash && $head_slash) {
            $ret = $path1 . substr($path2, 1);
        } else if ($tail_slash || $head_slash) {
            $ret = $path1 . $path2;
        } else {
            $ret = $path1 . '/' . $path2;
        }

        return $ret;
    }


    /**
     *
     *  @access public
     *  @param  string $csv
     *  @return string
     */
    function escapeFeed($csv) {
        while (preg_match('/^([\w\W]*,?)("(?:[^"]|"{3})*?[\r\n](?:[^"]|"{3})*?"(?:[,\r\n]))([\w\W]*)$/', $csv, $matches) != 0) {
            return MyApp_Util::escapeFeed($matches[1] . MyApp_Util::feedToString($matches[2]) . $matches[3]);
        }
        return $csv;
    }

    /**
     *
     *  @access public
     *  @param  string
     *  @return string
     */
    function feedToString($part) {
        $part = preg_replace('/\r\n/', "\\r\\n", $part);
        $part = preg_replace('/\r/', "\\r", $part);
        $part = preg_replace('/\n/', "\\n", $part);
        return $part;
    }

    /**
     *
     *  @access public
     *  @param  string
     *  @return string
     */
    function unescapeFeed($csv) {
        if (preg_match('/[\\\r]/', $csv)) {
            $csv = preg_replace('/\\\r/', "\r", $csv);
            $csv = preg_replace('/\\\n/', "\n", $csv);
        }
        return $csv;
    }


    /**
     *
     *  @access public
     *  @param  string
     *  @return array
     */
    function explodeByFeed($string) {
        $lines;
        $delimiters = array("\r\n", "\r", "\n");
        foreach ($delimiters as $delimiter) {
            if ($lines = explode($delimiter, $string)) {
                if (is_array($lines)) {
                    break;
                }
            }
        }
        if (!is_array($lines)) $lines[] = $lines;
        return $lines;
    }

    /**
     * @param resource handle
     * @param int length
     * @param string delimiter
     * @param string enclosure
     */
    function fgetcsv_reg(&$handle, $length = null, $d = ',', $e = '"') {
        $d = preg_quote($d);
        $e = preg_quote($e);
        $_line = "";
        $eof = false;
        while ($eof != true and !feof($handle)) {
            $_line .= (empty($length) ? fgets($handle) : fgets($handle, $length));
            $itemcnt = preg_match_all('/'.$e.'/', $_line, $dummy);
            if ($itemcnt % 2 == 0) $eof = true;
        }
        $_csv_line = preg_replace('/(?:\r\n|[\r\n])?$/', $d, trim($_line));
        $_csv_pattern = '/('.$e.'[^'.$e.']*(?:'.$e.$e.'[^'.$e.']*)*'.$e.'|[^'.$d.']*)'.$d.'/';
        preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
        $_csv_data = $_csv_matches[1];
        for($_csv_i=0;$_csv_i<count($_csv_data);$_csv_i++){
            $_csv_data[$_csv_i]=preg_replace('/^'.$e.'(.*)'.$e.'$/s','$1',$_csv_data[$_csv_i]);
            $_csv_data[$_csv_i]=str_replace($e.$e, $e, $_csv_data[$_csv_i]);
        }
        return empty($_line) ? false : $_csv_data;
    }
    
    /**
     * Get TSV file format an return a array with all data 
     * @param String $filename
     * @param Boolean $ignore 
     * 						True  - ignore all line empty 
     * 						False - all line with no data as array
     * @param Boolean $allow_comment
     * 						true  - comment with # in headline
     * 						False - no comment 
     * @return array data;
     */
	function fgetTsvAsArray($filename, $ignore = false, $allow_comment = false) {
		if( !(mb_detect_encoding(file_get_contents($filename)) == "SJIS") ) {
			return false;
		}
		function fgettsv_reg(&$handle, $head_line, $length = null, $d = "\t", $e = '"') {
			$d = preg_quote ( $d );
			$e = preg_quote ( $e );
			$_line = "";
			$_line .= (empty ( $length ) ? fgets ( $handle ) : fgets ( $handle, $length ));
			$_line = mb_convert_encoding($_line, "UTF-8", "sjis-win," . mb_detect_encoding($_line));
			
			if($head_line) {
				$__BOM = pack('CCC', 239, 187, 191);
				while(0 === strpos($_line, $__BOM)) {
    				$_line = substr($_line, 3);
				}
			}
			$itemcnt = preg_match_all ( '/' . $e . '/', $_line, $dummy );
			$_tsv_line = preg_replace ( '/(?:\\r\\n|[\\r\\n])?$/', $d, trim ( $_line ) );
			$_tsv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
			preg_match_all ( $_tsv_pattern, $_tsv_line, $_tsv_matches );
			$_tsv_data = $_tsv_matches [1];
			for($_tsv_i = 0; $_tsv_i < count ( $_tsv_data ); $_tsv_i ++) {
				$_tsv_data [$_tsv_i] = preg_replace ( '/^' . $e . '(.*)' . $e . '$/s', '$1', $_tsv_data [$_tsv_i] );
			}
			return empty ( $_line ) ? false : $_tsv_data;
		}
		$tsv = array (array () );
		$fp = fopen ( $filename, "rb" );
		$i = 0;
		$head_line = true;
		$line_number = 0;
		while ( $data = fgettsv_reg ( $fp, $head_line , null ) ) {
			$line_number++;
			$head_line = false;
			if ( $ignore && count ( $data ) == 1 && $data [0] == null ) {
				continue;
			}
			$comment_pattern = '/^(?![ \t]*[#]).*$/';
			$data[0] = mb_convert_kana($data[0], 'as');
			if ( $allow_comment && (!preg_match($comment_pattern, $data[0]) ) ) {
				continue;
			}
			$j = 0;
			$data[] = $line_number;
			foreach ( $data as $strData ) {
				$tsv [$i] [$j ++] = $strData;
			}
			$i ++;
		}
		fclose ( $fp );
		return $tsv;
	}
    /**
     * 
     * 
     * @param mixed $item_id
     * @return
     */
    function isDuplicateView($item_id)
    {
        $ctl = Ethna_Controller::getInstance();
        $session = $ctl->getSession();
        
        $session->start();
        
        $last_view_item_id = $session->get('__last_view_item_id');
        
        $session->set('__last_view_item_id', $item_id);
        
        return $last_view_item_id == $item_id;
    }
    
    /**
     * 
     * 
     * @param string $msg
     */
    function timestamp($msg="")
    {
        static $start_time = 0;
        static $last_time = 0;
        static $count = 1;
        
        $cur_time = microtime(true);
        if ($start_time == 0) $start_time = $cur_time;
        
        $total_time = $cur_time - $start_time;
        $gap_time = $last_time == 0 ? 0 : $cur_time - $last_time;
        $last_time = $cur_time;
        
        $str = sprintf("######## TIMESTAMP [%d]%s total_time:%f gap_time:%f", $count, $msg, $total_time, $gap_time);
        $count++;
        
        $this->backend->log(LOG_DEBUG, $str);
    }
    
    function mb_trim($str, $chars="\s　"){
        $str = mb_ereg_replace("^[$chars]+", "", $str);
        $str = mb_ereg_replace("[$chars]+$", "", $str);
        return $str;
    }    
    
    function check_Image_File($path, $pattern, $flags = 0){

        $arr_filename = array();
        $dir_path = MyApp_Util::joinPath($this->backend->getConfig()->get('document_root') 
                                        , $this->backend->getConfig()->get('img_path'));
        if(!empty($path)){
            $dir_path = MyApp_Util::joinPath($dir_path, $path);
        }

        foreach ( glob($dir_path.$pattern, $flags) as $filename ) {
            $arr_filename[] = basename($filename);
        
        }
        return $arr_filename;
    }    
 
	/**
	* isFirefox
	* @return true; is firefox
	* 		   false; not firefox
	*/
	function isFirefox(){
		return preg_match('/Firefox/i', $_SERVER['HTTP_USER_AGENT']);
	}
	/**
	 * is Internet Explorer
	 * @return true; is Internet Explorer
	 * 		   false; not Internet Explorer
	 */
	function isIE(){
		return preg_match('/MSIE/i', $_SERVER['HTTP_USER_AGENT']);
	}
	/**
	 * is Chrome
	 * @return true; is Chrome
	 * 		   false; not Chrome
	 */
	function isChrome(){
		return preg_match('/Chrome/i',$_SERVER['HTTP_USER_AGENT']);
	}
	/**
	 * is Safari
	 * @return true; is Safari
	 * 		   false; not Safari
	 */
	function isSafari(){
		return preg_match('/Safari/i',$_SERVER['HTTP_USER_AGENT']) && !preg_match('/Chrome/i',$_SERVER['HTTP_USER_AGENT']);
	}
	/**
	 * is Opera
	 * @return true; is Opera
	 * 		   false; not Opera
	 */
	function isOpera(){
		return preg_match('/Opera/i',$_SERVER['HTTP_USER_AGENT']);
	}

	/**
	 * get mail format encoding
	 * @param String $str String content format
	 * @return String
	 */
	function getFormatMailEncoding($str) {
		if(MyApp_Util::isIE() || MyApp_Util::isChrome() || MyApp_Util::isSafari()) {
			$str = mb_convert_encoding($str, "SJIS", 'UTF-8');
		}
		return rawurlencode($str);
	}
	
 	/**
 	 * Check Vendor Char in String
 	 * @param String $vars String check
 	 * @return false:  no matched
 	 * 		   String: first String vendor char matched  
 	 */
 	function checkVendorChar($vars) {
 		$null = false;
    	$string = mb_convert_encoding($vars, 'eucjp-win', 'utf-8');
        for ($i = 0, $j = 0; $i < strlen($string); $i++, $j++) {
            $c = ord($string{$i});
            if ($c < 0x80) {
            } else if ($c == 0x8e) {
                $i++;
            } else if ($c == 0x8f && $i < strlen($string) - 2 && (
                    (ord($string{$i + 1}) == 0xa2 && ord($string{$i + 2}) == 0xf1) ||
                    (ord($string{$i + 1}) == 0xf3 && ord($string{$i + 2}) >= 0xf3 && ord($string{$i + 2}) <= 0xfe) ||
                    (ord($string{$i + 1}) == 0xf4 && ord($string{$i + 2}) >= 0xa1 && ord($string{$i + 2}) <= 0xfe)
                )) {
                return mb_substr($vars, $j, 1, 'utf-8');
            } else if ($c == 0xad || ($c >= 0xf9 && $c <= 0xfc)) {
                return mb_substr($vars, $j, 1, 'utf-8');
            } else {
                $i++;
            }
        }

        return $null;	
 	}
 	/**
 	 * check string matched in file
 	 * @param String $str check
 	 * @param String $pathFile path
 	 * @return false; not matched
 	 * 		   String: matched
 	 */
 	function _Str_Pos_Kinshi($str, $pathFile = null) {
 		$null = false;
        $base_dirs = $this->backend->getConfig()->get('base_path');
        $bubun_file = $base_dirs."/etc/strstr.txt";
        $pathFile = (!$pathFile) ? $bubun_file : $pathFile;
        $fp = fopen( $pathFile, "r" );
        if($fp){
            while (!feof($fp)) {
                $data = fgets($fp, filesize($pathFile));
                if(@strstr($str, trim($data))){
                    return trim($data);
                    break;
                }
            }
            return $null;
        } else {
            return $null;
        }
 	}
 	
    /**
     *  check open admin area
     *
     *  @access public
     */
    function isOpenAdminArea() {
        if (preg_match('/^\/openadmin/', $_SERVER['REQUEST_URI'])) {
            return true;
        }
        return false;
    }
	
 	/**
 	 * checkMailAddress 
 	 * @access public
 	 * @param  string  $mailaddress
 	 * @return true: matched, false: not matched
 	 */
 	function checkMailAddress($mailaddress) {
 		if (preg_match('/^([a-z0-9_]|\-|\.)+@(([a-z0-9_]|\-)+\.)+[a-z]{2,6}$/i', $mailaddress)) {
            return true;
        }
        return false;
 	}
 	/**
 	 * get IP client.
 	 */
    function getIpAddresses() {
        
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $remote_address = $_SERVER['HTTP_CLIENT_IP'];
        } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $remote_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $remote_address = $_SERVER['REMOTE_ADDR'];
        }
        return $remote_address;
    }
    /**
     * valid source ip.
     * 
     * @param String $check_ip to check.
     * @param Array $ip_table source.
     */
    function isValidSourceIp($check_ip, $ip_table) {
        foreach ($ip_table as $ip) {
            $ip = trim($ip);
            if (strcmp($check_ip, $ip) == 0 || Net_IPv4::ipInNetwork($check_ip, $ip)) {
                return true;
            }
        }
        return false;
    }
    function getOnelyText($strText) {
        $strText = html_entity_decode(strip_tags($strText));
        $strText = preg_replace('/{emoji=([a-z0-9_, ]+)}/i', '', $strText);
        $strText = preg_replace('/{_IMG_([0-9, ]+)_([0-9, ]+)_([a-z0-9., ]+)_}/i', '', $strText);
        $strText = mb_convert_encoding($strText, "UTF-8");
        return $strText;
    }
    /**
     * Omitted whitespace, newline, tab html in Title.
     * @param $title
     * @return String $title
     */
    function formatPageTitle($title) {
        $title = html_entity_decode(strip_tags($title));
        $title = preg_replace("/　/", '', $title);
        $title = preg_replace("/\s+/", '', $title);
        $title = mb_convert_encoding($title, "UTF-8");
        return $title;
    }
    
    /**
     * Omitted whitespace, newline, tab html, emoji and specify image in Description.
     * @param $desc
     * @return String $desc
     */
    function formatDescripton($desc) {
        $desc = html_entity_decode(strip_tags($desc));
        $desc = preg_replace('/　/', '', $desc);
        $desc = preg_replace('/\s+/', '', $desc);
        $desc = preg_replace('/{emoji=([a-z0-9_, ]+)}/i', '', $desc);
        $desc = preg_replace('/{_IMG_([0-9, ]+)_([0-9, ]+)_([a-z0-9., ]+)_}/i', '', $desc);
        $desc = mb_convert_encoding($desc, "UTF-8");
        return $desc;
    }
    /**
     * get Operating System
     * 
     */
    function getOSAndVersion() {
        $user_agent     =   $_SERVER['HTTP_USER_AGENT']; 
        $os_platform    =   "Unknown";
        $os_version     =   "Unknown";
        if (preg_match('/win/i', $user_agent)) {
            $os_platform = 'W';
            if (preg_match('/windows nt 6.2/i', $user_agent)) {
                $os_version = "8";
            } else if (preg_match('/windows nt 6.1/i', $user_agent)) {
                $os_version = "7";
            } else if (preg_match('/windows nt 6.0/i', $user_agent)) {
                $os_version = "Vista";
            } else if (preg_match('/windows nt 5.2/i', $user_agent)) {
                $os_version = "Server 2003/XP x64";
            } else if (preg_match('/windows nt 5.1/i', $user_agent) || preg_match('/windows xp/i', $user_agent)) {
                $os_version =  "XP";
            } else if (preg_match('/windows nt 5.0/i', $user_agent)) {
                $os_version = "2000";
            } else if (preg_match('/windows me/i', $user_agent)) {
                $os_version = "ME";
            } else if (preg_match('/win98/i', $user_agent)) {
                $os_version = "98";
            } else if (preg_match('/win95/i', $user_agent)) {
                $os_version = "95";
            } else if (preg_match('/win16/i', $user_agent)) {
                $os_version = "3.11";
            }
        } else if (preg_match('/mac/i', $user_agent)) {
            $os_platform = 'M';
            if (preg_match('/macintosh/i', $user_agent)) {
                $os_version = "OS X";
            } else if (preg_match('/mac_powerpc/i', $user_agent)) {
                $os_version .= "OS 9";
            }
        } else if (preg_match('/linux/i', $user_agent)) {
            $os_platform    =   "L";
            $os_version     =   "Linux";
        } else if (preg_match('/ipad/i', $user_agent)) {
            $os_platform    =   "I";
            $os_version     =   "Ipad";
        } else if (preg_match('/android/i', $user_agent)) {
            $os_platform    =   "A";
            $os_version     =   "Android";
        }
        return array(
            'platform'       =>  $os_platform,
            'version'   =>  $os_version
        );
    }
}
?>
